import 'dart:async';

import 'package:flutter_axrjc/datasource/network/api/UserApi.dart';
import 'package:flutter_axrjc/datasource/network/api/UserApi.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/util/Util.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import 'state.dart';

class ChangePasswordLogic extends GetxController {
  final ChangePasswordState state = ChangePasswordState();
  @override
  void onInit() {
    super.onInit();
    UserApi.getUser().then((value) {
      state.phone.value = value?.customerInfo?.telPhone ?? "";
    });
  }

  Future<void> change() async {
    if (state.yzm.value.isEmpty) {
      EasyLoading.showToast("请输入验证码");
      return;
    }
    if (state.password.value.isEmpty) {
      EasyLoading.showToast("请输入新密码");
      return;
    }
    if (!Util.isPassword(state.password.value)) {
      EasyLoading.showToast("密码为6到12位字母和数字组合");
      return;
    }

    if (state.password2.value.isEmpty) {
      EasyLoading.showToast("请再次输入新密码");
      return;
    }
    if (state.password.value != state.password2.value) {
      EasyLoading.showToast("两次密码不一致");
      return;
    }
    try {
      await UserApi.changePassword(
          yzm: state.yzm.value, password: state.password.value);
      EasyLoading.showToast("修改成功，请重新登录");
      UserApi.logout();
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
  }

  Timer? _timer;

  void startTimer() {
    if (!state.isTimerActive.value) {
      state.isTimerActive.value = true;
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (state.countDown.value == 0) {
          state.countDown.value = 60;
          state.isTimerActive.value = false;
          state.buttonText.value = "获取验证码";
          _timer?.cancel();
        } else {
          state.countDown.value--;
          state.buttonText.value = "${state.countDown.value}s后重新获取";
        }
      });
    }
  }

  Future<void> sendSmsCode() async {
    if (state.isTimerActive.value) {
      EasyLoading.showToast("${state.countDown.value}s后可重新获取");
      return;
    }
    if (state.phone.value.isEmpty) {
      EasyLoading.showToast("请输入手机号");
      return;
    }
    try {
      await UserApi.sendCode(telPhone: state.phone.value);
      startTimer();
    } catch (e) {
      print(e);
    }
  }

  @override
  void onClose() {
    super.onClose();
    _timer?.cancel();
  }
}
